--[[
    author : wenshengyu
    date   : 2021-10-22
]]
local require = require
local cjson = require("cjson.safe")
local log   = require("modules.commhm.log")
local utils = require("modules.commhm.utils")
local auth  = require("modules.commhm.auth_comm_checker")
local biz_utils = require("modules.business_common.business_utils")

local ngx = ngx
local type = type
local pairs = pairs
local ipairs = ipairs
local tonumber = tonumber
local table = table
local tostring = table.tostring
local loadstring = loadstring

local FOO = {_VERSION = "0.0.1"}

FOO.send = function(result, data)
    result = result or {}
    result = type(result) ~= "table" and {ret = result} or result
    local response = utils.table_value_copy(result)

    if data ~= nil then response.data = data end

    if ngx.ctx.m_params.json == "1" then
        -- json ajax 跨域
        ngx.header["Access-Control-Allow-Origin"] = "*"
        ngx.header["Server"] = "php"

        ngx.say(utils.table2json(response))
    elseif ngx.ctx.m_params.log == "1" then
        -- log
        log.debug("<br><br>=========================return begin========")
        utils.var_dump(response)
        log.debug("=========================return end========<br><br>")
    else
        -- lua
        ngx.say(tostring(response))
    end
end

FOO.recv = function()
    ngx.ctx.m_params = ngx.req.get_uri_args();
    ngx.ctx.log          = tonumber(ngx.ctx.m_params.log) or 0
    ngx.ctx.m_params.uin = tonumber(ngx.ctx.m_params.uin) or 0
    ngx.ctx.xff          = biz_utils.real_client_ip() or 'nil';

    if not auth.ns_http_sec.decodeS7Url() then
        log.error("decodeS7Url fail.")
        return false
    end

    if "POST" == ngx.var.request_method then

        ngx.req.read_body()
        local t = cjson.decode(ngx.req.get_body_data())

        if t == nil then
            t = loadstring(ngx.req.get_body_data()) --此时尝试用这种格式
        end
        log.debug("recv:" .. ngx.req.get_body_data())
        if not t then
            log.error("decode body failed.")
            return false
        end
        -- 合并参数
        for k, v in pairs(t) do
            ngx.ctx.m_params[k] = v
        end
    end
    return true
end

return FOO
